<template>
  <div>
    <div v-show="false">
      <button @click="printEditorHtml">print html</button>
      <button @click="getEditorText">print text</button>
    </div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :default-config="toolbarConfig"
      />
      <!-- 编辑器 -->
      <Editor
        v-model="html"
        :style="{ height: height, 'overflow-y': 'hidden', 'border': '1px solid #e8e8e8' }"
        :default-config="editorConfig"
        @onChange="onChange"
        @onCreated="onCreated"
      />
      <div class="error-tip">
        <div id="errorMsg" />
      </div>
      <el-tooltip>
        <div slot="content">
          #({{ $t('空格') }}): {{ $t('多级标题') }}<br>
          >({{ $t('空格') }}): {{ $t('文本引用') }}<br>
          ```({{ $t('回车') }}): {{ $t('代码块') }}<br>
          {{ $t('拖入或粘贴, 将保留图片在编辑器中') }}
        </div>
        <i class="el-icon-question" style="position: absolute;right: 10px;font-size: 14px;height: 24px;margin-top: -17px;" />
      </el-tooltip>
      <div v-show="false" style="margin-top: 10px">
        <textarea
          v-model="html"
          readonly
          style="width: 100%; height: 200px; outline: none"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
import markdownModule from '@wangeditor/plugin-md'
import linkCardModule from '@wangeditor/plugin-link-card'
import { getToken } from '@/utils/auth'
import config from '@/utils/config'
Boot.registerModule(linkCardModule)
Boot.registerModule(attachmentModule)
Boot.registerModule(markdownModule)
export default {
  name: 'MyEditor',
  components: { Editor, Toolbar },
  props: {
    value: {
      type: String,
      default: () => ''
    },
    height: {
      type: String,
      default: () => '500px'
    }
  },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {
        insertKeys: {
          // 自定义插入的位置
          index: 20,
          // “上传附件”菜单
          keys: ['uploadAttachment']
        },
        // 排除菜单
        excludeKeys: ['fullScreen']
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,
        // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
        hoverbarKeys: {
          attachment: {
            // “下载附件”菜单
            menuKeys: ['downloadAttachment']
          }
        },
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          // 上传图片
          uploadImage: {
            // 上传图片配置
            server: config.baseURL + '/file/fileBase/uploadNotesFile',
            fieldName: 'file',
            // 粘贴截图最大2MB
            maxFileSize: 2 * 1024 * 1024,
            // 最多上传个数
            maxNumberOfFiles: 1,
            // 文件类型
            allowedFileTypes: ['image/*'],
            // 上传参数
            mate: {
              Authorization: getToken()
            },
            headers: {
              'Authorization': 'Bearer ' + getToken()
            },
            // mate在链接上拼接
            metaWithUrl: false,
            // 跨域
            withCredentials: false,
            // 超时
            timeout: 30000,
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            // 上传之前触发
            onBeforeUpload(file) {
              // file 选中的文件，格式如 { key: file }
              return file

              // 可以 return
              // 1. return file 或者 new 一个 file ，接下来将上传
              // 2. return false ，不上传这个 file
            },

            // 上传进度的回调函数
            onProgress(progress) {
              // progress 是 0-100 的数字
              console.log('progress', progress)
            },

            // 单个文件上传成功之后
            onSuccess(file, res) {
              console.log('上传成功', res)
            },

            // 单个文件上传失败
            onFailed(file, res) {
              document.getElementById('errorMsg').innerText = '上传失败'
              setTimeout(() => {
                document.getElementById('errorMsg').innerText = ''
              }, 2000)
              console.log('上传失败', res)
            },

            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              console.log('上传出错', err, res)
              if (res === undefined) {
                if (err.message.includes('exceeds maximum allowed size')) {
                  document.getElementById('errorMsg').innerText = '请上传小于2MB的文件'
                  setTimeout(() => {
                    document.getElementById('errorMsg').innerText = ''
                  }, 2000)
                } else {
                  document.getElementById('errorMsg').innerText = '操作错误'
                  setTimeout(() => {
                    document.getElementById('errorMsg').innerText = ''
                  }, 2000)
                }
              }
            }
          },
          // 上传附件
          uploadAttachment: {
            // 服务端地址
            server: config.baseURL + '/file/fileBase/uploadNotesFile',
            // 100s
            timeout: 200 * 1000,
            fieldName: 'file',
            headers: {
              'Authorization': 'Bearer ' + getToken()
            },
            maxFileSize: 10 * 1024 * 1024, // 10M
            onBeforeUpload(file) {
              console.log('onBeforeUpload', file)
              return file // 上传 file 文件
              // return false // 会阻止上传
            },
            onProgress(progress) {
              console.log('onProgress', progress)
            },
            onSuccess(file, res) {
              console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
              alert(res.message)
              console.log('onFailed', file, res)
            },
            onError(file, err, res) {
              alert(err.message)
              console.error('onError', file, err, res)
            },
            // 插入到编辑器后的回调
            onInsertedAttachment(elem) {
              console.log('inserted attachment', elem)
            }
          }
        }
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        var token = 'Authorization=' + getToken()
        this.html = val.replaceAll('${∞}', token)
      }
    }
  },
  mounted() {
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    // 组件销毁时，及时销毁 editor ，重要！！！
    editor.destroy()
  },
  methods: {
    onCreated(editor) {
      // 【注意】一定要用 Object.seal() 否则会报错
      this.editor = Object.seal(editor)
    },
    onChange(editor) {
      // onChange 时获取编辑器最新内容
      var text = editor.getHtml()
      var token = 'Authorization=' + getToken()
      text = text.replaceAll('${∞}', token)
      // console.log('onChange', text)
      this.$emit('change', text)
    },
    getEditorText() {
      // const editor = this.editor
      // if (editor == null) return
      // 执行 editor API
      // console.log(editor.getText())
    },
    printEditorHtml() {
      const editor = this.editor
      if (editor == null) return
      // 执行 editor API
      console.log(editor.getHtml())
    }
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.error-tip {
  position: inherit;
  border: 1px solid rgb(232, 232, 232);
  text-align: center;
  font-size: 14px;
  height: 24px;
  line-height: 1.7;
  color: orange;
}
</style>
